import Mock from 'mockjs';

const url = {
  list: /\/mock\/list/, // 列表数据
};

// 提取
function extract(url: string): { [key: string]: string } {
  const params: { [key: string]: string } = {};
  const queryString = url.split('?')[1];
  if (queryString) {
    const keyValuePairs = queryString.split('&');
    keyValuePairs.forEach((pair) => {
      const [key, value] = pair.split('=');
      params[decodeURIComponent(key)] = decodeURIComponent(value);
    });
  }
  return params;
}

// 切片

function slice<T>(array: T[], start: number, count: number): T[] {
  const slicedArray: T[] = [];
  const endIndex = Math.min(start + count, array.length);
  for (let i = start; i < endIndex; i++) {
    slicedArray.push(array[i]);
  }
  return slicedArray;
}

Mock.mock(url.list, 'get', (options) => {
  const params: Record<string, unknown> = extract(options.url);

  const dataBase = [
    {
      id: 1,
      title: '任务1',
      status: 1,
      add_time: '2024-08-25 06:00:00',
      remark: '跑步',
    },
    {
      id: 2,
      title: '任务2',
      status: 2,
      add_time: '2024-08-26 12:00:00',
      remark: '吃饭',
    },
    {
      id: 3,
      title: '任务3',
      status: 2,
      add_time: '2024-08-27 14:00:00',
      remark: '学习',
    },
    {
      id: 3,
      title: '任务4',
      status: 2,
      add_time: '2024-08-28 17:00:00',
      remark: '游泳',
    },
    {
      id: 4,
      title: '任务5',
      status: 1,
      add_time: '2024-08-29 23:00:00',
      remark: '睡觉',
    },
  ];

  let list = slice(
    dataBase,
    Number(((params.page as number) - 1) * (params.limit as number)),
    Number(params.limit as number)
  );

  if (params.keyword !== '') {
    list = list.filter((item) => {
      return item.title.includes(params.keyword as string);
    });
  }

  if (params.status !== '') {
    list = list.filter((item) => {
      return item.status === Number(params.status);
    });
  }

  if (params.date !== '') {
    const [startTime, endTime] = (params.date as string).split(',');
    list = list.filter((item) => {
      const date = new Date(item.add_time.split('-').join('/')).getTime();
      return date >= Number(startTime) && date <= Number(endTime);
    });
  }

  return {
    code: 1,
    data: { list },
    msg: '',
  };
});
